/**
 * - pages subpackages tabBar
 * - 合并数据
 * - 生成临时文件
 * - 替换主题中设置的变量
 * - 条件编译
 * - 生成 uni-app 规范的 pages.json
 */
import {
  OPT_KEYS,
  isEmptyObject
} from '@shared';
import {
  injectPlatforms
} from '@core/util';
import {
  groupRouters,
  groupSubpackages,
  orderRoutersByPlatforms
} from './routers';
import {
  parseRouters
} from './extension';

export function composePagesJson(routers, profile) {
  const routerExtras = parseRouters(routers);
  const appRouters = groupRouters(routers, profile.tabBar);
  const pages = orderRoutersByPlatforms(appRouters.pages);
  const subpackages = groupSubpackages(appRouters.subpackages).map(
    subpackage => {
      subpackage.pages = orderRoutersByPlatforms(subpackage.pages);
      return subpackage;
    }
  );

  let options = {};
  OPT_KEYS.forEach(key => {
    options[key] = profile[key];
  });

  // 注意使用 subPackages
  let pagesJson = {
    pages,
    ...profile.ext
  };
  if (subpackages.length) {
    pagesJson.subPackages = subpackages;
  }
  if (!isEmptyObject(appRouters.tabBar)) {
    pagesJson.tabBar = appRouters.tabBar;
  }
  for (let key in options) {
    if (!isEmptyObject(options[key])) {
      pagesJson[key] = options[key];
    }
  }

  const pagesJsonString = JSON.stringify(pagesJson, null, 2);

  return {
    pagesJson: injectPlatforms(pagesJsonString),
    extras: {
      ...routerExtras
    }
  };
}
